#include "Mesh.h"

#include <sstream>

// TODO: remove after debugging
#include <OgreLogManager.h>
#define LOG(M) Ogre::LogManager::getSingleton().logMessage(M)
///////////////////////////////

namespace MHX
{
	bool Mesh::parse(LineIterator &line)
	{
		enum MeshReadMode { ReadGeneric, ReadVerts, ReadFaces, ReadTextureFace};
		int mode = ReadGeneric;

		try
		{
			if(line->size() > 1)
				name = line->at(1);

			while(1)
			{
				line++;
				// End of section (or mesh)?
				if(line->at(0).compare("end") == 0 && line->size() > 1)
				{
					if((line->at(1).compare("Verts") == 0 && mode == ReadVerts)
					   || (line->at(1).compare("Faces") == 0 && mode == ReadFaces)
					   || (line->at(1).compare("MeshTextureFaceLayer") == 0 && mode == ReadTextureFace)
					  )
						mode = ReadGeneric;

					// End of mesh
					else if(line->at(1).compare("Mesh") == 0)
						break;

					continue;
				}

				else if(mode == ReadFaces)
				{
					if(line->at(0).compare("f") == 0) // Read in face
					{
						MHX::Face f;

						if(f.parse(*line))
							faces.push_back(f);
					}

					else if(line->at(0).compare("ft") == 0) // Read in face prop
					{
						MHX::FaceProperty fp;

						if(fp.parse(*line))
							faceProperties.push_back(fp);
					}
				}

				// TODO: Read in as actual TextureFaceLayer, UV as data member
				else if(mode == ReadTextureFace) // UV values
				{
					if(line->at(0).compare("vt") == 0)
					{
						MHX::FaceUV fuv;

						if(fuv.parse(*line))
							uv.push_back(fuv);
					}
				}

				else if(mode == ReadVerts) // Vertices
				{
					if(line->at(0).compare("v") == 0)
					{
						MHX::Vert v;
						
						if(v.parse(*line))
							verts.push_back(v);
					}
				}

				else if(mode == ReadGeneric) // Beginning of section?
				{
					if(line->at(0).compare("Verts") == 0)
						mode = ReadVerts;
					else if(line->at(0).compare("Faces") == 0)
						mode = ReadFaces;
					else if(line->at(0).compare("MeshTextureFaceLayer") == 0)
						mode = ReadTextureFace;
					else if(line->at(0).compare("Material") == 0)
					{
						MHX::Material mat;

						if(mat.parse(*line))
							materials.push_back(mat);
					}

					continue;
				}
			}
		}
		catch(std::exception &e) // reached end of file without encountering "End mesh"
		{
			return false;
		}

		return true;
	}
}